<template>
    <div class="box">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" style="width: 400px;">
            <el-form-item label="账号" prop="username">
                <el-input v-model="form.username" placeholder="请输入账号" auto-complete="username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="form.password" placeholder="请输入密码"
                    auto-complete="current-password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleRegister" style="width: 100%;">
                    注册
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";

const form = ref({
    username: "",
    password: ""
});

// 表单验证规则
const rules = reactive({
    username: [
        { required: true, message: "请输入账号", trigger: "blur" },
        { min: 3, max: 20, message: "长度在3-20个字符", trigger: "blur" }
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 20, message: "密码长度6-20位", trigger: "blur" }
    ]
});

const handleRegister = async () => {
    try {
        const response = await axios.post(
            "http://localhost:8000/plates/register",
            null,
            {
                auth: {
                    username: form.value.username,
                    password: form.value.password,
                },
                headers: {
                    "Content-Type": "application/json",
                },
            }
        );
        if (response.status === 200) {
            await router.push({ name: "login" });
            ElMessage.success("注册成功");
        } else {
            if (response.status === 401) {
                ElMessage.error("用户名或密码错误");
            } else {
                ElMessage.error("注册失败，状态码：" + response.status);
            }
        }
    } catch (error) {
        console.error("注册请求失败:", error);
        if (error.response?.status === 401) {
            ElMessage.error("用户名或密码错误");
        } else {
            ElMessage.error("注册失败，请重试");
        }
    }
};
</script>

<style scoped>
.box {
    min-height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-form {
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-link {
    cursor: pointer;
}
</style>